package org.base.common.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.base.common.annotation.Log;
import org.base.common.util.*;
import org.base.sys.enums.OpStatus;
import org.base.sys.pojo.SysOpLog;
import org.base.sys.service.SysOpLogService;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;

@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class LogAspect {


    private SysOpLogService opLogService;

    private ObjectMapper objectMapper;

    // 配置织入点
    @Pointcut("@annotation(org.base.common.annotation.Log)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            final HttpServletRequest request = RequestUtils.getRequest();
            // *========数据库日志=========*//
            SysOpLog opLog = new SysOpLog();
            opLog.setStatus(OpStatus.SUCCESS.getCode());
            // 请求的地址
            String ip = IpUtils.getIpAddr(request);
            opLog.setOpIp(ip);
            // 返回参数
            opLog.setJsonResult(objectMapper.writeValueAsString(jsonResult));
            opLog.setOpUrl(request.getRequestURI());
            opLog.setOpName(UserUtils.getUserName());
            if (e != null) {
                opLog.setStatus(OpStatus.FAIL.getCode());
                opLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            opLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            opLog.setRequestMethod(request.getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(controllerLog, opLog, joinPoint);
            // 保存数据库
            AsyncUtils.execute(() -> {
                opLog.setOpLocation(AddressUtils.getRealAddressByIP(opLog.getOpIp()));
                opLogService.save(opLog);
            });
        } catch (Exception exp) {
            log.error(exp.getMessage(), exp);
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log 日志
     * @throws Exception
     */
    public void getControllerMethodDescription(Log log, SysOpLog opLog, JoinPoint joinPoint) throws Exception {
        // 设置action动作
        opLog.setBusinessType(log.bizType().getCode());
        // 设置标题
        if (StringUtils.isNotBlank(log.value())) {
            opLog.setTitle(log.value());
        } else {
            opLog.setTitle(getMethod(joinPoint).getDeclaringClass().getSimpleName());
        }
        // 设置操作人类别
        opLog.setOpType(log.opType().getCode());
        // 是否需要保存request，参数和值
        if (log.saveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(opLog);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param opLog
     */
    private void setRequestValue(SysOpLog opLog) throws JsonProcessingException {
        Map<String, String[]> map = RequestUtils.getRequest().getParameterMap();
        String params = objectMapper.writeValueAsString(map);
        opLog.setOpParam(StringUtils.substring(params, 0, 2000));
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Method method = getMethod(joinPoint);
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }

    private Method getMethod(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        return method;
    }
}
